<template>
  <div>
    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-input v-model="data.name" style="width: 240px; margin-right: 10px" placeholder="请输入班级名查询" :prefix-icon="Search"></el-input>
      <el-select v-model="data.specialityId" style="width: 240px; margin-right: 10px" placeholder="请选择专业查询">
        <el-option v-for="item in specialityList" :key="item.specialityId" :label="item.name"
          :value="item.specialityId"></el-option>
      </el-select>
      <el-select v-model="data.teacherId" style="width: 250px; margin-right: 10px" placeholder="请选择教师查询">
        <el-option v-for="item in teacherList" :key="item.teaId" :label="item.realname" :value="item.teaId"></el-option>
      </el-select>
      <el-button type="primary" @click="load">查询</el-button>
      <el-button type="info" style="margin: 0 10px" @click="reset">重置</el-button>
    </div>

    <div class="card"
      style="margin-bottom: 10px;background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <div style="margin-bottom: 10px">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" style="margin-left: 10px" @click="delBatch">批量删除</el-button>
        <el-button type="info" style="margin-left: 10px">导 入</el-button>
        <el-button type="success" style="margin-left: 10px">导 出</el-button>
      </div>
      <el-table :data="data.tableData" stripe @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column type="selection" width="55" />
        <el-table-column label="编号" prop="classId"></el-table-column>
        <el-table-column label="班级名" prop="name"></el-table-column>
        <el-table-column label="班级描述" prop="description">
          <template #default="scope">
            <span v-if="scope.row?.description && scope.row.description.trim() !== ''">
              {{ scope.row.description }}
            </span>
            <span v-else>
              无
            </span>
          </template>
        </el-table-column>
        <el-table-column label="教师" prop="teacherName">
          <template #default="scope">
            <span v-if="scope.row?.teacherName && scope.row.teacherName.trim() !== ''">
              {{ scope.row.teacherName }}
            </span>
            <span v-else>
              无
            </span>
          </template>
        </el-table-column>
        <el-table-column label="所属专业" prop="specialityName"></el-table-column>
        <el-table-column label="操作" align="center" width="160">
          <template #default="scope">
            <el-button type="primary" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(scope.row.classId)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="data.isEdit ? '编辑班级信息' : '新增班级信息'" width="600" v-model="data.formVisible"
      :close-on-click-modal="false" destroy-on-close>
      <el-form :model="data.form" style="padding: 20px 40px 0px 0px" :rules="data.rules" ref="formRef" label-width="120px">
        <!-- 学号 - 新增时可输入，编辑时禁用 -->
        <el-form-item label="班级名" prop="name">
          <el-input v-model="data.form.name" :disabled="data.isEdit" />
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input v-model="data.form.description" />
        </el-form-item>

        <el-form-item label="教师" prop="teacherId" v-if="data.isEdit">
          <el-select v-model="data.form.teacherId" placeholder="请选择教师">
            <el-option v-for="item in teacherList" :key="item.teaId" :label="item.realname" :value="item.teaId" />
          </el-select>
        </el-form-item>

        <el-form-item label="所属专业" prop="specialityId">
          <el-select v-model="data.form.specialityId" placeholder="请选择专业">
            <el-option v-for="item in specialityList" :key="item.specialityId" :label="item.name"
              :value="item.specialityId" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">
            {{ data.isEdit ? '保存修改' : '新增班级' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <div class="card" style="background: linear-gradient(to bottom, #f5f3f2, #92bdce);border: 1px solid;">
      <el-pagination @current-change="load" @size-change="load" v-model:current-page="data.pageNum"
        v-model:page-size="data.pageSize" :page-sizes="[5, 10, 15, 20]" layout="total, sizes, prev, pager, next, jumper"
        :total="data.total" />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from "vue";
import alovaInstance from "@/utils/request";
import { ElMessage, ElMessageBox } from "element-plus";
import {Search} from "@element-plus/icons-vue";

// 文件上传的接口地址
const user = JSON.parse(window.localStorage.getItem("credit-system-user"));
const specialityList = ref([]);
const teacherList = ref([]);
// 定义表单引用
const formRef = ref(null);

const data = reactive({
  pageNum: 1,
  pageSize: 5,
  total: 0,
  formVisible: false,
  isEdit: false,
  specialityId: '',
  form: {
    name: '',
    description: '',
    specialityId: '',
    teacherId: '',
  },
  rules: {
    name: [
      { required: true, message: '请输入班级名', trigger: 'blur' },
    ],
    teacherId: [
      { required: true, message: '请选择教师', trigger: 'blur' }
    ],
    specialityId: [
      { required: true, message: '请选择专业', trigger: 'blur' }
    ]
  },
  tableData: [],
  ids: [],
})

// 加载专业列表（不分页）
const loadSpecialityList = () => {
  alovaInstance.Get('/collegeAdminSpeciality/selectSpeciality', {
    params: {
      collegeId: user.collegeId
    }
  }).then(res => {
    specialityList.value = res.data.list || [];
    console.log(res.data.list)
  }).catch(error => {
    console.error('获取专业列表失败:', error);
    ElMessage.error(error.message);
  });
}

// 加载教师列表（不分页）
const loadTeacherList = () => {
  alovaInstance.Get('/teacher/selectTeacher', {
    params: {
      collegeId: user.collegeId
    }
  }).then(res => {
    teacherList.value = res.data.list || [];
    console.log(res.data.list)
  }).catch(error => {
    console.error('获取教师列表失败:', error);
    ElMessage.error(error.message);
  });
}

// 分页查询班级
const load = () => {
  console.log("-----------:", data.specialityId)
  alovaInstance.Get('/collegeAdminClasses/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      specialityId: data.specialityId,
      teacherId: data.teacherId,
      collegeId: user.collegeId
    }
  }).then(res => {
    console.log("res.data-----:", res.data)
    data.tableData = res.data?.list || [];
    data.total = res.data?.total || 0;
  }).catch(error => {
    console.error('请求班级列表失败:', error);
    ElMessage.error(error.message);
  });
}

// 新增
const handleAdd = () => {
  data.isEdit = false;
  data.form = {
    name: '',
    description: '',
    specialityId: '',
    teacherId: '',
  };
  data.formVisible = true;
}

// 编辑
const handleEdit = (row) => {
  data.isEdit = true;
  data.form = JSON.parse(JSON.stringify(row));

  // 确保专业列表已加载
  if (specialityList.value.length === 0) {
    loadSpecialityList();
  }

  // 确保教师列表已加载
  if (teacherList.value.length === 0) {
    loadTeacherList();
  }

  data.formVisible = true;
}

// 提交表单
const submitForm = () => {
  formRef.value.validate(valid => {
    if (valid) {
      if (data.isEdit) {
        update();
      } else {
        add();
      }
    }
  });
}

// 修改后的 update 方法
const update = () => {
  data.form.updateBy = user.username;
  alovaInstance.Put(`/collegeAdminClasses/updateClasses`, data.form)
    .then(res => {
      console.log('更新接口返回:', res);
      if (res.code === '200') {
        // 先关闭对话框再加载数据和显示消息
        data.formVisible = false;
        // 添加短暂延迟确保组件完全卸载
        setTimeout(() => {
          load();
          ElMessage.success('操作成功');
        }, 100);
      } else {
        ElMessage.error(res.msg || '更新失败');
      }
    })
    .catch(error => {
      ElMessage.error('更新班级失败: ' + error.message);
    });
  setTimeout(() => { location.reload(); }, 500);
}

// 同样修改 add 方法
const add = () => {
  data.form.createBy = user.username;
  alovaInstance.Post(`/collegeAdminClasses/addOneClasses?collegeId=${user.collegeId}`, data.form)
    .then(res => {
      if (res.code === '200') {
        data.formVisible = false;
        setTimeout(() => {
          load();
          ElMessage.success('操作成功');
        }, 100);
      } else {
        ElMessage.error(res.msg || '新增失败');
      }
    })
    .catch(error => {
      ElMessage.error('新增班级失败: ' + error.message);
    });
  setTimeout(() => { location.reload(); }, 500);
}

// 删除
const handleDelete = (classId) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗?', '删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/collegeAdminClasses/deleteClasses/${classId}?updateBy=${user.username}`).then(res => {
      if (res.code === '200') {
        load();
        ElMessage.success('操作成功');
        setTimeout(() => { location.reload(); }, 500);
      } else {
        ElMessage.error(res.msg || '删除失败');
      }
    }).catch(error => {
      console.error('删除班级失败:', error);
      ElMessage.error('删除班级失败，请重试');
    });
  }).catch(() => { });
}

// 批量选择（保持不变）
const handleSelectionChange = (rows) => {  //返回选中的行对象数组
  console.log(rows)
  //从选中的行对象中取出所有的id，组成一个新数组！
  //使用map函数(数组内置函数)
  //遍历rows数组，将每个元素（行对象）的id属性值提取出来，组成一个新的数组。并赋值给存储id的数组中
  data.ids = rows.map(row => row.classId)
  console.log(data.ids)
}

// 批量删除
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选中需删除的数据')
    return
  }
  ElMessageBox.confirm('批量删除数据后无法恢复，您确认删除吗？', '批量删除确认', { type: 'warning' }).then(() => {
    alovaInstance.Put(`/collegeAdminClasses/deleteBatch/${user.username}`, data.ids).then(res => {
      if (res.code === '200') {
        ElMessage.success('删除成功')
        setTimeout(() => { location.reload(); }, 500);
      }
    }).catch(error => {
      console.error('请求失败:', error);
      ElMessage.error(error.message || '网络错误，请稍后重试');
    })
  }).catch()
}

// 重置
const reset = () => {
  data.form = {
    name: '',
    description: '',
    specialityId: '',
    teacherId: '',
  };
  data.name = '';
  data.specialityId = '';
  data.teacherId = '';
  load();
}

// 生命周期钩子：组件挂载后初始化数据
onMounted(() => {
  loadSpecialityList(); // 加载专业列表
  loadTeacherList();    // 加载教师列表
  load();               // 加载班级数据
})
</script>